package com.icloud.cer.rest.msg;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EncrytServer {
	private static final Logger log = LoggerFactory.getLogger(EncrytServer.class);
	private IoHandlerAdapter handler;
	private	InetSocketAddress localAddress;
	private boolean reuseAddress = true;
	
	private IoFilterChainBuilder filterChainBuilder;
	
	private Map<String, ? extends IoFilter> filters;
	
	private SocketAcceptor acceptor;
	
	
	public void setHandler(IoHandlerAdapter handler) {
		this.handler = handler;
	}

	public void setFilterChainBuilder(IoFilterChainBuilder filterChainBuilder) {
		this.filterChainBuilder = filterChainBuilder;
	}
	
	public void setReuseAddress(boolean reuseAddress) {
		this.reuseAddress = reuseAddress;
	}

	public void setFilters(Map<String, ? extends IoFilter> filters) {
		this.filters = filters;
	}

	public void setLocalAddress(InetSocketAddress localAddress) {
		this.localAddress = localAddress;
	}

	public EncrytServer() {
		
	}
	
	public void init() {
		startServer();
	}
	
	private void startServer() {
		log.info("server starting......");
		acceptor = new NioSocketAcceptor();
		acceptor.setFilterChainBuilder(filterChainBuilder);
        acceptor.setHandler(handler);
        acceptor.setReuseAddress(reuseAddress);
        acceptor.setDefaultLocalAddress(localAddress);
        acceptor.getSessionConfig().setReadBufferSize( 2048 );
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        
        try {
			acceptor.bind();
			InetSocketAddress address = acceptor.getLocalAddress();
			log.info("server started." + address.getHostName() + ",port:" + address.getPort());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Map<Long, IoSession> getSessionMap() {
		return acceptor.getManagedSessions();
	}
}
